<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/23
 * Time: 8:40
 */

namespace app\api\controller\v2;


use app\api\lib\exception\MissException;
use app\api\lib\exception\SuccessMessage;
use app\api\model\CouponTickets;
use app\api\service\TokenService;
use think\Db;

class CouponController extends BaseController
{
    public function _initialize()
    {
        $this->uid = TokenService::getCurrentUid();
    }

    //我的优惠券
    public function getMyCoupon()
    {
        $coupons = CouponTickets::getUserAvailableCoupon($this->uid);
        if(empty($coupons)){
            throw new MissException(['msg'=>'当前用户没有可用的优惠券']);
        }
        $result = Db::table('coupon_tickets')->where('id','in',$coupons)->where(['is_use'=>0])->field(['id','activity_id','cate_id','coupon_category_id'])->select();
        foreach ($result as $key => $value){
            $result[$key]['coupon'] = Db::table('coupon_category')->where('id',$value['coupon_category_id'])->field(['low_price','name','amount_cash','discount_ticket','coupon_cate_cate'])->find();
            $result[$key]['coupon']['id'] = $value['id'];
            $result[$key]['coupon']['low_price'] = floor($result[$key]['coupon']['low_price']);
            $result[$key]['coupon']['amount_cash'] = floor($result[$key]['coupon']['amount_cash']);
            $result[$key]['coupon']['end_time'] = Db::table('activity')->where('id',$value['activity_id'])->field(['end_time'])->find()['end_time'];
            $result[$key]['coupon']['start_time'] = Db::table('activity')->where('id',$value['activity_id'])->field(['start_time'])->find()['start_time'];
            $result[$key] = skinArray(visibleArray( $result[$key],['coupon']),'coupon');
        }
        throw new SuccessMessage([
            'data' => $result,
        ]);
    }
}